package org.springleaf.core.mvc.controller;

import org.springleaf.core.mvc.service.BaseService;
import org.springleaf.utils.ClassUtils;
import org.springleaf.utils.SpringBeanFactoryUtils;

/**
 * 提供模型操作的Controller
 * 
 * @author leaf
 */
@SuppressWarnings("unchecked")
public abstract class ModelController<T> extends BaseController {

	/** 当前类的泛型类型 */
	private Class<T> type;

	/**
	 * 当前的model bean名
	 */
	private String beanName;

	/**
	 * 当前类的泛型模型对应的服务类
	 */
	private BaseService<T> service;

	public ModelController() {
		super();
	}
	
	/**
	 * 得到对应泛型模型的服务bean
	 */
	protected BaseService<T> getService() {
		if (this.service == null) {
			this.type = ClassUtils.getGeneric(this);
			this.beanName = ClassUtils.getSimpleBeanName(this.type);
			BaseService<T> service = SpringBeanFactoryUtils.getBean(beanName
					+ "Service");
			this.service = service;
		}
		return this.service;
	}

	/**
	 * 设置服务类
	 */
	protected void setService(BaseService<T> service) {
		this.service = service;
	}

	public String getBeanName() {
		if(this.beanName == null){
			this.beanName = ClassUtils.getSimpleBeanName(this.getType());
		}
		return beanName;
	}

	public void setBeanName(String beanName) {
		this.beanName = beanName;
	}

	public Class<T> getType() {
		if(this.type == null){
			this.type = ClassUtils.getGeneric(this);
		}
		return type;
	}
}
